import React, { Component } from 'react';
import { Layout, Drawer, Menu, Dropdown, Icon, Col, Button, Table, Select, Row, DatePicker, Form, message } from 'antd';
import "antd/dist/antd.css";
import { BrowserRouter as Router, Route, HashRouter } from "react-router-dom";
import axios from '../../rudexRou/urlHttp.js';
import { uncompileStr, VerifySessionTime, getCookie, compileStr, delCookie, getResponseUrl, getLinkToUrl, devProTest, findConfig, getHeaderParams } from '../../rudexRou/OperatesCookie.js';
import routers from '../../rudexRou/routers.js';
import { dataAxios } from '../../rudexRou/request.js';
import zhCN from 'antd/es/locale/zh_CN';
import 'moment/locale/zh-cn';
import moment from 'moment';
import echarts from 'echarts';
import '../../componentCss/component.css';
const { Header, Footer, Content, Sider } = Layout;
const { SubMenu } = Menu;
const { Option } = Select;
const costRole = JSON.parse(sessionStorage.getItem("costRole"))
const costBu = costRole[0].buInfo;
const { Column, ColumnGroup } = Table;
class TotalCost extends Component {
    constructor(props) {
        super(props);
        this.state = {
            IsBg: false,
            bdno: costRole[0].bdno === "全部" ? "全部" : costRole[0].bdno,
            //  buno: "全部",
            buno: costBu != undefined && costBu.length > 0 ? costBu[0].buno : "全部",
            bdlist: [],  //BD列表
            bulist: [], //BU列表
            //如果当前年的当前月是1月则取年份取去年
            Year: new Date().getMonth() == 0 ? moment((new Date().getFullYear() - 1).toString()) : moment(new Date().getFullYear().toString()),
            startYear: new Date().getMonth() == 0 ? moment((new Date().getFullYear() - 2)).toString(): moment((new Date().getFullYear() - 1).toString()),
            feeList: [],
            maxMonth: 0,
            startMonthValue: 1,
            //如果当前年的当前月是1月则月份取去年12月
            endMonthValue: new Date().getMonth() == 0 ? 12 : new Date().getMonth(),
            monthList: [],
            loading: false,
            columns: [],
            clientWidth:0
        };

    }
    componentWillMount() {
    }
    componentDidMount() {
        this.setState({
            clientWidth: document.body.clientWidth
        })
        window.onresize = () => {
            this.setState({
                clientWidth: document.body.clientWidth
            })
        }
        this.getMonthList()
        costRole.map((item, index) => {
            if (item.bdno === "全部") {
                this.setState({ IsBg: true })
            }
        });
        let value = costRole[0].bdno === "全部" ? "" : costRole[0].bdno
        if (costBu != undefined && costBu.length > 0) {
            this.setState({
                bulist: costBu
            });
        } else {
            this.getBUInfo(value);
        }
        this.getData()

    }
    getMonthList() {
        let month = [];
        for (let i = 0; i < 12; i++) {
            month.push(i + 1);
        }
        this.setState({
            monthList: month
        });
    }
    getparams = () => {
        let values = this.refs.form.getFieldsValue();
        values.bdno = values.bdno == "全部" ? "" : values.bdno
        values.buno = values.buno == "全部" ? "" : values.buno
        values.year = Number(moment(values.year).format("YYYY"))
        values.startYear= Number(moment(values.startYear).format("YYYY"))
        // values.DutyName=this.state.DutyName;
        // values.BDBUCU=this.state.BDBUCU;
        // values.FAM_Year = moment(values.FAM_Year).format("YYYY")
        // values.DetailTypes="Other,Society";
        // values.pageNum="1";
        // values.pageSize="30"
        return values
    }
    getInitialColumns(startMonth, maxMonth) {
        let initialColumns = [
            {
                title: '分类',
                dataIndex: 'Deptype',
                key: 'Deptype',
                width: 150,
                // align: "center",
                ellipsis: true
            }
        ]
        for (let i = startMonth; i < (maxMonth + 1); i++) {
            let obj = {
                title: i + "月(元)",
                dataIndex: i,
                key: i,
                width: 100,
                align: "center",
                ellipsis: true
            }
            initialColumns.push(obj)
        }
        let avgMonth = {
            title: '均值(元)',
            dataIndex: 'average',
            key: 'average',
            width: 100,
            align: "center",
            ellipsis: true,
            fixed: "right",
        }
        let totalObj = {
            title: '汇总(元)',
            dataIndex: 'totalCost',
            key: 'totalCost',
            width: 100,
            align: "center",
            fixed: "right",
        }
        initialColumns.push(avgMonth, totalObj)

        return initialColumns;
    }
    getData = () => {

        this.setState({ loading: true })
        let url = `${getResponseUrl('TotalCost')}/total/getYearTotalCost`;
        let params = this.getparams()
        let leftData = []
        let rightData = []
        let echartLeft = echarts.init(document.getElementById('echartLeft'));
        let echartRight = echarts.init(document.getElementById('echartRight'));
        echartLeft.showLoading()
        echartRight.showLoading()
        dataAxios({
            url: url,
            method: 'post',
            data: params
        }).then((response) => {
            if (response.status === 200) {
                if (response.data) {
                    let MagData = {
                        endYearIsplay: response.data.monthlyIsPayStatistics.totalCost,//结束年客户支付费用
                        endYear: response.data.monthlyStatistics.totalCost,//结束年非客户支付费用
                        endYearMag: response.data.monthlyTotalStatistics.totalCost,//结束年总费用
                        startYearIsplay: response.data.lastYearMonthlyIsPayStatistics.totalCost,//开始年客户支付费用
                        startYear: response.data.lastYearMonthlyStatistics.totalCost,//开始年非客户支付费用
                        startYearMag: response.data.lastYearMonthlyTotalStatistics.totalCost,//开始年总费用
                    }
                    leftData.push(MagData)
                    rightData.push(response.data.feeProportion)
                    echartLeft.hideLoading()
                    echartRight.hideLoading()
                    this.getleftEchart(leftData, echartLeft)
                    this.getRightEchart(rightData, echartRight)
                    //table 数据
                    let TabelData = [];
                    //开始年非客户支付费用
                    response.data.lastYearMonthlyStatistics.Deptype = moment(this.state.startYear).format("YYYY") + "年非客户支付费用"
                    TabelData.push(response.data.lastYearMonthlyStatistics)
                    //结束年非客户支付费用
                    response.data.monthlyStatistics.Deptype = moment(this.state.Year).format("YYYY") + "年非客户支付费用"
                    TabelData.push(response.data.monthlyStatistics)
                    //开始年客户支付费用
                    response.data.lastYearMonthlyIsPayStatistics.Deptype = moment(this.state.startYear).format("YYYY") + "年客户支付费用"
                    TabelData.push(response.data.lastYearMonthlyIsPayStatistics)
                    //结束年客户支付费用
                    response.data.monthlyIsPayStatistics.Deptype = moment(this.state.Year).format("YYYY") + "年客户支付费用"
                    TabelData.push(response.data.monthlyIsPayStatistics)
                    //开始年总费用
                    response.data.lastYearMonthlyTotalStatistics.Deptype =  moment(this.state.startYear).format("YYYY")+ "年总费用"
                    TabelData.push(response.data.lastYearMonthlyTotalStatistics)
                    //结束年总费用
                    response.data.monthlyTotalStatistics.Deptype = moment(this.state.Year).format("YYYY") + "年总费用"
                    TabelData.push(response.data.monthlyTotalStatistics)
                    let finalColumns = this.getInitialColumns(this.state.startMonthValue, this.state.endMonthValue)
                    this.setState({ feeList: TabelData, loading: false, columns: finalColumns })

                }
            }
        })
    }
    getleftEchart = (data, echartsDom) => {
        let lastYearData = []
        let endYearData = []
        if (data.length > 0) {
            lastYearData.push((data[0].startYear / 10000) ? (data[0].startYear / 10000).toFixed(1) : 0)
            lastYearData.push((data[0].startYearIsplay / 10000) ? (data[0].startYearIsplay / 10000).toFixed(1) : 0)
            lastYearData.push((data[0].startYearMag / 10000) ? (data[0].startYearMag / 10000).toFixed(1) : 0)
            endYearData.push((data[0].endYear / 10000) ? (data[0].endYear / 10000).toFixed(1) : 0)
            endYearData.push((data[0].endYearIsplay / 10000) ? (data[0].endYearIsplay / 10000).toFixed(1) : 0)
            endYearData.push((data[0].endYearMag / 10000) ? (data[0].endYearMag / 10000).toFixed(1) : 0)
        }
        let No = this.state.bdno == "全部" && this.state.buno == "全部" ? "" : this.state.bdno != "全部" && this.state.buno == "全部" ? this.state.bdno : this.state.buno
        let titleName = this.getBuBdNameByNo(No)
        let monthRange = this.state.startMonthValue == this.state.endMonthValue ? this.state.endMonthValue + "月" : this.state.startMonthValue + "-" + this.state.endMonthValue + "月"
        // if(this.state.bdno!="全部"&&)
        let option = {
            title: {
                text: "费用同比" + moment(this.state.startYear).format("YYYY")+"&&"+ moment(this.state.Year).format("YYYY") + "年" + monthRange,
                x: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
            },
            toolbox: {
                show: true,
                feature: {
                    saveAsImage: { show: true }
                },
                right: "2%",
            },
            legend: {
                data: [moment(this.state.startYear).format("YYYY")  + "年", moment(this.state.Year).format("YYYY") + "年"],
                bottom: 0
            },
            color: ['#66fddb', '#b570ed', "#F46F6F"],
            xAxis: {
                type: 'category',
                axisLabel: {
                    interval: 0
                },
                data: ["非客户支付", "客户支付", "总费用"]
            },
            yAxis: [
                {
                    type: 'value',
                    name: "(万元)"
                },
            ],
            series:
                [

                    {
                        name:moment(this.state.startYear).format("YYYY")  + "年",
                        type: 'bar',
                        barWidth: 60,
                        data: lastYearData,
                        itemStyle: {
                            normal: {
                                label: {
                                    show: true,
                                    position: 'top',
                                }
                            }
                        }
                    },
                    {
                        name: moment(this.state.Year).format("YYYY") + "年",
                        type: 'bar',
                        barWidth: 60,
                        data: endYearData,
                        itemStyle: {
                            normal: {
                                label: {
                                    show: true,
                                    position: 'top',
                                }
                            }
                        }
                    },
                ]
        };
        echartsDom.setOption(option, true);
        window.addEventListener("resize", function () {
            echartsDom.resize();
        });
    }
    getRightEchart = (data, echartsDom) => {
        let cusData = [];
        let CusDatafee = [];
        let totalData = [];
        let xData = [];
        let params = this.getparams();
        if (data.length > 0) {
            cusData.push((data[0].monthlyFluctuates / 10000) ? (data[0].monthlyFluctuates / 10000).toFixed(1) : 0)//非客户支付费用
            cusData.push((data[0].monthlyIsPayFluctuates / 10000) ? (data[0].monthlyIsPayFluctuates / 10000).toFixed(1) : 0)//客户支付费用
            cusData.push((data[0].yearTotalCostFluctuates / 10000) ? (data[0].yearTotalCostFluctuates / 10000).toFixed(1) : 0)//总费用
            CusDatafee.push(data[0].monthlyIncrease.replace("%", ""));//非客户费用占比
            CusDatafee.push(data[0].monthlyIsPayIncrease.replace("%", ""));//客户费用占比
            CusDatafee.push(data[0].yearTotalCostIncrease.replace("%", ""));//总费用占比
        }
        xData = Array.from(new Set(xData))
        let monthRange = this.state.startMonthValue == this.state.endMonthValue ? this.state.endMonthValue + "月" : this.state.startMonthValue + "-" + this.state.endMonthValue + "月"
        let option = {
            title: {
                text: "费用偏差" + moment(this.state.startYear).format("YYYY")+"&&"+ moment(this.state.Year).format("YYYY") + "年" + monthRange,
                x: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function (params) {
                    let tip = '';
                    if (params != null && params.length > 0) {
                        for (let i = 0; i < params.length; i++) {
                            if (params[i].seriesName == '偏差占比') {
                                tip += params[i].marker+ params[i].seriesName + ': ' + params[i].value + '%<br>';
                            } else {
                                tip += params[i].marker+ params[i].seriesName + ': ' + params[i].value+"<br>" ;
                            }
                        }
                    }
                    return tip;
                }
            },
            toolbox: {
                show: true,
                feature: {
                    saveAsImage: { show: true }
                },
                right: "2%",
            },
            legend: {
                data: ["费用偏差", "偏差占比"],
                bottom: 0
            },
            color: ['#66fddb', '#b570ed', "#F46F6F"],
            xAxis: {
                type: 'category',
                data: ["非客户支付", "客户支付", "总费用"]
            },
            yAxis: [
                {
                    type: 'value',
                    name: "(万元)",
                  
                },
                {
                    type: 'value',
                    name: '',
                    axisLabel: {
                        formatter: '{value}%'
                    },
                    splitLine: {
                        show: false   //去掉网格线
                    }
                },
            ],
            series:
                [

                    {
                        name: "费用偏差",
                        type: 'bar',
                        data: cusData,
                        barWidth: 60,
                        itemStyle: {
                            normal: {
                                label: {
                                    show: true,
                                    position: 'top',
                                    // offset: [0, -20]
                                }
                            }
                        }
                    },
                    {
                        name: "偏差占比",
                        type: 'line',
                        yAxisIndex: 1,
                        data: CusDatafee,
                        itemStyle: {
                            normal: {
                                label: {
                                    show: true,
                                    position: 'top',
                                    formatter: function (val) {
                                        return val.data + '%'
                                    }
                                }
                            }
                        }
                    },
                ]
        };
        echartsDom.setOption(option, true);
        window.addEventListener("resize", function () {
            echartsDom.resize();
        });
    }
    getBuBdNameByNo = (no) => {
        let BdBuName = "MAG"
        if (this.state.bdno != "全部" && this.state.buno == "全部") {
            costRole.map((item) => {
                if (no === item.bdno) {
                    BdBuName = item.bdname
                }
            })
        } else if (this.state.bdno != "全部" && this.state.buno != "全部") {
            let data = this.state.bulist
            data.map((res) => {
                if (no == res.buno) {
                    BdBuName = res.buname
                }
            })
        }
        return BdBuName
    }
    getBUInfo(value) {
        let _this = this;
        let url = `${getResponseUrl('TotalCost')}/buinfo`;
        let params = {
            "bdno": (value === '全部' ? '' : value) || ''
        };
        dataAxios({
            url: url,
            method: 'post',
            data: params
        }).then(response => {
            if (response.status === 200) {
                let result = response.data;
                //点击请选择，则会显示全部数据
                let emptyValue = { buno: '全部', buname: '全部' };
                result.unshift(emptyValue);
                _this.setState({
                    bulist: result
                });
            }
        }).catch(error => {
            console.log(error);
        });
    }
    //事业本部值改变的时候
    bdonChange = (value) => {
        //选中之后赋值
        this.setState({
            bdno: value,
            buno: "全部"
        });
        this.refs.form.setFieldsValue({
            buno: "全部",
        });
        // if (value === "全部") {
        //     this.setState({
        //         buno: "全部"
        //     });
        //     this.refs.form.setFieldsValue({
        //         buno: "全部",
        //     });
        // }
        if (costBu != undefined && costBu.length > 0) {

            costRole.map((item) => {
                if (item.bdno == value) {
                    this.setState({
                        bulist: item.buInfo,
                        buno: item.buInfo[0].buno
                    });
                }
            })
        } else {
            //清空事业部的信息
            this.setState({
                buno: '全部'
            })
            this.getBUInfo(value);
        }

    }
    //事业部值改变的时候
    buonChange = (value) => {
        this.setState({
            buno: value
        });
    }
    clearValue = (value) => {
        this.setState({
            Year: moment(value).format("YYYY"),
            // startYear: moment(value).format("YYYY") - 1
        })
    }
    clearStartValue = (value) => {
        this.setState({
             startYear: moment(value).format("YYYY")
        })
    }
    startDisabledDate=Value=>{
        if (!Value) {
            return false;
        }
        return Value.valueOf() >= moment(this.state.Year).valueOf();
    }
    disabledEndDate = Value => {
        if (!Value) {
            return false;
        }
        return Value.valueOf() <= moment(this.state.startYear).valueOf();
    };
    formatPrice(num) {
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num))
            num = "0";
        let sign = (num == (num = Math.abs(num)));
        num = Math.floor(num * 100 + 0.50000000001);
        num = Math.floor(num / 100).toString();
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
            num = num.substring(0, num.length - (4 * i + 3)) + ',' +
                num.substring(num.length - (4 * i + 3));
        }

        return (((sign) ? '' : '-') + num);
    }
    getMonthList() {
        let month = [];
        for (let i = 0; i < 12; i++) {
            month.push(i + 1);
        }
        this.setState({
            monthList: month
        });
    }
    endMonthOnChange(value) {
        if (value > this.state.startMonthValue || value == this.state.startMonthValue) {
            this.setState({
                endMonthValue: value
            });
        } else {
            this.refs.form.setFieldsValue({
                endMonth: new Date().getMonth() == 0 ? 12 : new Date().getMonth(), //如果当前年的当前月是1月则月份取去年12月
            });
            message.warning("结束月份要大于开始月份,请重新选择")
        }

    }
    startMonthOnChange(value) {
        if (value < this.state.endMonthValue || value == this.state.endMonthValue) {
            this.setState({
                startMonthValue: value
            });
        } else {
            this.refs.form.setFieldsValue({
                startMonth: 1,
            });
            message.warning("开始月份要小于结束月份,请重新选择")
        }

    }
    getMonthList() {
        let month = [];
        for (let i = 0; i < 12; i++) {
            month.push(i + 1);
        }
        this.setState({
            monthList: month
        });
    }
    search() {
        this.getData()
    }
    render() {
        return <div>
            <div className='myProjectsFont'>
                <span>运营</span>
                <span className="icoRight"></span>
                <span>费用分析管理</span>
                <span className="icoRight"></span>
                <span>总体费用分析</span>
                <span className="icoRight"></span>
                <span style={{ color: '#40B7FF' }}>年度总费用统计</span>
            </div>
            <div className='tabstyle'>

                <div className="bigContent1" id="projectDetail">
                    <Form
                        // form={form}
                        ref="form"
                        name="advanced_search"
                        className="ant-advanced-search-form"
                        onFinish={this.onFinish}
                    >
                        <Row gutter={24}>
                            <Col span={5}>
                                <Form.Item
                                    name="bdno"
                                    label="事业本部"
                                    rules={[
                                        {
                                            required: false,
                                        },
                                    ]}
                                    initialValue={this.state.bdno}
                                >
                                    <Select dropdownMatchSelectWidth={false} style={{ width: "90%", }} className="bussineSelect1" onChange={this.bdonChange.bind(this)}>
                                        {
                                            costRole.map((item, index) =>
                                                <Option key={index} value={item.bdno}>{item.bdname}</Option>
                                            )
                                        }
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={5}>
                                <Form.Item
                                    name="buno"
                                    label="&nbsp;&nbsp;事业部"
                                    rules={[
                                        {
                                            required: false,
                                        },
                                    ]}
                                    initialValue={this.state.buno}
                                >
                                    <Select dropdownMatchSelectWidth={false} style={{ width: "90%" }} disabled={this.state.bdno == "全部"} className="bussineSelect1" onChange={this.buonChange.bind(this)}>
                                        {
                                            this.state.bulist.map((item, index) =>
                                                <Option key={index} value={item.buno}>{item.buname}</Option>
                                            )
                                        }
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={4}>
                                <Form.Item
                                    name="startYear"
                                    label="同比年"
                                    rules={[
                                        {
                                            required: false,
                                        },
                                    ]}
                                    initialValue={this.state.startYear}
                                >
                                    <DatePicker
                                      disabledDate={this.startDisabledDate}
                                        picker="year"
                                        placeholder='请选择年份'
                                        style={{ width: "90%" }}
                                        onChange={this.clearStartValue}
                                        allowClear={false}
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={4}>
                                <Form.Item
                                    name="year"
                                    label="年份"
                                    rules={[
                                        {
                                            required: false,
                                        },
                                    ]}
                                    initialValue={this.state.Year}
                                >
                                    <DatePicker
                                      disabledDate={this.disabledEndDate}
                                        picker="year"
                                        placeholder='请选择年份'
                                        style={{ width: "90%" }}
                                        onChange={this.clearValue}
                                        allowClear={false}
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={4}>
                                <Form.Item
                                    name="startMonth"
                                    label="开始月份"
                                    rules={[
                                        {
                                            required: false,
                                        },
                                    ]}
                                    initialValue={this.state.startMonthValue}
                                >
                                    <Select style={{ width: "90%" }} onChange={this.startMonthOnChange.bind(this)}>
                                        {
                                            this.state.monthList.map((item, index) =>
                                                <Option key={item} value={item}>{item + '月'}</Option>
                                            )
                                        }
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={4}>
                                <Form.Item
                                    name="endMonth"
                                    label="结束月份"
                                    rules={[
                                        {
                                            required: false,
                                        },
                                    ]}
                                    initialValue={this.state.endMonthValue}
                                >
                                    <Select style={{ width: "90%" }} onChange={this.endMonthOnChange.bind(this)}>
                                        {
                                            this.state.monthList.map((item, index) =>
                                                <Option key={item} value={item}>{item + '月'}</Option>
                                            )
                                        }
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={1} >
                                <Row gutter={24}>
                                    <Col span={24}>
                                        <Button type="primary" onClick={() => this.search()} style={{ verticalAlign: "top" }}>
                                            搜索
                                            </Button>
                                    </Col>
                                </Row>
                            </Col>
                        </Row>
                    </Form>

                    <div className="echartsDiff">
                        <div id="echartLeft" className='echartsLeft' style={{ height: "320px" }}></div>
                        <div id="echartRight" className="echartsRight" style={{ height: "320px" }}></div>
                    </div>
                    <div style={{ marginTop: "20px" }}>
                        <div className="tableDiff">
                            <Table
                                loading={this.state.loading}
                                dataSource={this.state.feeList}
                                scroll={{ x: (this.state.columns.length) * 100 > this.state.clientWidth ? (this.state.columns.length) * 100 : null }}
                                bordered
                                columns={this.state.columns}
                                 rowKey={(record) => record.Deptype}
                                pagination={false}>
                            </Table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    }
}
export default TotalCost;

